import importlib
import logging
import pkgutil

from sqlalchemy import select, inspect

from core.database import DBConnect
from core.models import Config
from lib.social.social import register_social_provider

# Package.
package_name = 'lib.social.providers'

# pkgutil 获取子目录的模块作为.
package = importlib.import_module(package_name)
for _, module_name, _ in pkgutil.walk_packages(package.__path__):
    full_module_name = f"{package_name}.{module_name}"
    imported_module = importlib.import_module(full_module_name)

__all__ = [
    "google",
    "facebook",
    "naver",
    "kakao",
    "twitter",
]


with DBConnect().sessionLocal() as db:
    # 在安装之前， config 没有桌子，所以检查一下.
    if inspect(DBConnect().engine).has_table(DBConnect().table_prefix + "config"):
        try:
            config = db.scalar(select(Config))
            # 启动服务器时，会调用社交登录设置.
            register_social_provider(config)
        except Exception as e:
            logging.warning("无法调出社交登录设置. " + str(e.args[0]))
